﻿Imports System.Data.Entity.Infrastructure
Imports System.Data.Common
Imports System.Configuration
Imports System.Data.Entity

Public Class FakeConnectionConnectionFactory
    Implements IDbConnectionFactory

    Private Shared _defaultConnectionFactory As IDbConnectionFactory

    Public Shared Sub RegisterFactory(Of TContext As DbContext)()
        Dim registeredProvidersDataSet As DataSet = DirectCast(ConfigurationManager.GetSection("system.data"), DataSet)
        Dim registeredProviders As DataRowCollection = registeredProvidersDataSet.Tables(0).Rows

        Try
            registeredProviders.Add({"FakeDbProviderFactory",
                                    "Generates Fake Db Objects for use in test code.  Does not make any actual Db connections.",
                                    "FakeDbConnection.FakeDbProviderFactory",
                                    "FakeDbConnection.FakeDbProviderFactory, FakeDbConnection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"})
        Catch ex As ConstraintException
            'already added
        End Try

        _defaultConnectionFactory = Database.DefaultConnectionFactory
        Database.DefaultConnectionFactory = New FakeConnectionConnectionFactory()

        Database.SetInitializer(Of TContext)(New DoNotCreateDatabaseInitializer(Of TContext)())
    End Sub

    Public Shared Sub UnregisterFactory(Of TContext)()
        Database.DefaultConnectionFactory = _defaultConnectionFactory
        Database.SetInitializer(Of TContext)(New CreateDatabaseIfNotExists(Of TContext))
    End Sub

    Public Function CreateConnection(sqlServerYear As String) As DbConnection Implements IDbConnectionFactory.CreateConnection
        If Not {"2000", "2005", "2008"}.Contains(sqlServerYear) Then
            Throw New NotSupportedException("Only supports MS SQL Server 2000, 2005, and 2008")
        End If

        Return New FakeDbConnection(sqlServerYear)
    End Function
End Class
